package com.uuah.server.util.spring;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.UnsupportedEncodingException;

import org.springframework.core.io.AbstractResource;

import com.uuah.utils.IOUtils;

public class CachedResource extends AbstractResource {

	private static final String DEFAULT_DESCRIPTION = "cached in-memory resource";

	private final byte[] buffer;
	private final String description;

	public CachedResource(byte[] source) {
		this(source, null);
	}

	public CachedResource(String source, String encoding)
			throws UnsupportedEncodingException {
		this(source.trim().getBytes(encoding), DEFAULT_DESCRIPTION);
	}

	public CachedResource(byte[] source, String description) {
		this.buffer = source;
		this.description = description;
	}

	public CachedResource(Reader reader, String encoding) throws IOException {
		this(IOUtils.toByteArray(reader, encoding), DEFAULT_DESCRIPTION);
	}

	public String getDescription() {
		return (description == null) ? "" : description;
	}

	public InputStream getInputStream() throws IOException {
		return new ByteArrayInputStream(buffer);
	}
}
